<template>
  <div class="tree-base">
    <ul>
      <li>
        <div class="tree-node" tabindex="1" @click="nodeClick" v-bind:name="treeData.name"  v-bind:node-id="treeData.id" v-bind:level="level"
             :style="{paddingLeft:level*15 + 'px'}"
             @mouseover="addIsVisible = true" @mouseleave="addIsVisible = false">
          <div style="display: flex; justify-content: space-between; width: 100%;">
            <div class="tree-node-content">{{treeData.name}}</div>
            <div v-if="addIsVisible && level === 1" class="tree-node-add" @click="addBtn" v-bind:node-id="treeData.id">+</div>
          </div>
        </div>
        <div class="tree-children">
          <tree v-for="item in treeData.children"
                v-if="isFolder"
                v-show="open"
                @nodeClick="innerNodeClick"
                :tree-data="item"
                :level="nextLevel"
                :keys="item"
          ></tree>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
  import IconButton from "./icon-button";
  import {ipcRenderer} from 'electron';

  export default {
    name: "tree",
    components: {
      IconButton,
    },
    props: {
      treeData: {
        type: Object
      },
      level: {
        type: Number,
        default: 1
      },
    },
    data() {
      return {
        open: false,
        addIsVisible: false,
        nextLevel: this.level + 1,
      }
    },
    created() {
    },
    computed: {
      isFolder: function () {
        return this.treeData.children
      }
    },
    methods: {
      nodeClick($event) {
        let node = $event.currentTarget;
        if (this.level > 1) {
          this.$emit('nodeClick', node, this.treeData.id);
        }
        if (this.isFolder) {
          this.open = !this.open;
        }
      },
      innerNodeClick(node) {
        this.$emit('nodeClick', node);
      },
      addBtn($event) {
        let node = $event.currentTarget;
        this.$emit('addBtn', node);
      }
    }
  }
</script>

<style scoped>
  .tree-base {
    margin: 0;
    width: 100%;
    overflow: hidden;
  }

  .tree-node {
    outline: none;
    display: flex;
    align-items: center;
    height: 40px;
    user-select: none;
    color: gray;
  }

  .tree-node:hover {
    background-color: rgba(240, 235, 239, 0.8);
  }

  .tree-node:focus {
    background-color: #DFDFD1;
  }

  .tree-node::before {
    content: '#';
    padding-right: 5px;
  }

  .tree-node-add {
    display: flex;
    cursor: pointer;
    justify-content: center;
    align-items: center;
    color: #743eea;
    width: 30px;
    margin-top: -5px;
    font-size: 20px;

  }

  .tree-children {
    width: 100%;
  }

  ul, li {
    list-style-type: none;
    width: 100%;
    margin: 0px;
    padding: 0;
    transition: 1.5s;
  }

  .tree-children {
    width: 100%;
  }

  .tree-children > .tree-base {
    /*padding-left: 15px;*/
  }

</style>
